from datetime import datetime

from sqlalchemy import Column, Integer, ForeignKey, Enum as SQLEnum, DECIMAL, DateTime, String, func
from sqlalchemy.orm import relationship
from enum import Enum

from backend.db.base import Base


class TransactionType(Enum):
    """交易类型"""
    RECHARGE = "recharge"  # 充值
    CONSUMPTION = "consumption"  # 消费
    REFUND = "refund"  # 退款


class Transaction(Base):
    """交易记录模型"""
    __tablename__ = 'Transaction'

    id = Column(Integer, primary_key=True, comment='交易id')
    member_id = Column(Integer, ForeignKey('member.id'), nullable=False, comment='会员id')
    transaction_type = Column(SQLEnum(TransactionType), nullable=False, comment='交易类型')
    amount = Column(DECIMAL(10, 2), nullable=False, comment='交易金额')
    transaction_state = Column(String(200), default='正常', nullable=False, comment='交易状态')
    description = Column(String(200), nullable=True, comment="交易描述")
    transaction_date = Column(DateTime, default=datetime.now(), nullable=False, comment="交易时间")

    def __repr__(self):
        return f"<Transaction(id={self.id}, 会员编号={self.member_id}, 交易类型={self.transaction_type.value}, 金额={self.amount})>"

    @property
    def zh_cn_display(self):
        """获取交易类型中文显示"""
        type_map = {
            TransactionType.RECHARGE: "充值",
            TransactionType.CONSUMPTION: "消费",
            TransactionType.REFUND: "退款"
        }
        return type_map.get(self.transaction_type, "未知")

    @property
    def amount_display(self):
        """获取金额显示格式"""
        if self.transaction_type == TransactionType.CONSUMPTION:
            return f"-¥{self.amount}"
        else:
            return f"+¥{self.amount}"
